// pages/businesscard/businesscard.js
import Wxml2Canvas from 'wxml2canvas';
import config from '~/configs/configs'
import basesup from '~/utils/supplier.js'
import baseuser from '~/utils/users.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        width:0,
        height:0,
        state:true,
        fileList: [],
        username:'',
        userDuties:'',
        userPhone:'',
        userWx:'',
        codeUrl:''
    },
    // afterRead(event) {
    // const { file } = event.detail;
    //   // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    //   wx.uploadFile({
    //     url:config.baseUrl + baseuser.adminossfileupload,
    //     filePath: file.url,
    //     name: 'wechatCode',
    //     formData: { user: 'test' },
    //     success(res) {
    //       // 上传完成需要更新 fileList
    //       const { fileList = [] } = this.data;
    //       fileList.push({ ...file, url: res.data });
    //       this.setData({ fileList });
    //     },
    //     fail(res){
    //       console.log(1);
    //       console.log(res);
    //     }
    //   });
    //   // console.log(file.url);
    // },
    // 保存
    afterRead(){
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera', 'album'],
            camera: 'back',
            success: (e) => {
              console.log('e when success:', e);
                // 上传当前图片
                wx.uploadFile({
                  url: config.baseUrl + baseuser.adminossfileupload, // 上传图片的服务器地址
                  filePath: e.tempFiles[0].tempFilePath,
                  name: 'file',
                  success: (uploadFileRes)=> {
                    console.log('res调用成功', uploadFileRes)
                    this.setData({
                      codeUrl:JSON.parse(uploadFileRes.data).data.map.url
                    })
                  },
                  fail: function (error) {
                    // 上传失败，处理失败情况
                    console.log('上传失败',error)
                  }
                });
            },
            fail: (e) => {
              console.log('e when fail', e);
            }
          })
    },
    //删除
    deleteUpload(){
        this.setData({
            codeUrl:''
        })
    },
   async saveBusinessCard(){
     let redata = await basesup.businessCard()
     console.log(redata)
     if (redata.data ===null) {
        wx.showToast({
            title: redata.message,
            icon: 'none',
            duration: 1500
        });
      
     } else{
        wx.showToast({
            title: '保存成功！',
            icon: 'none',
            duration: 1500
        });
     }
   },
    drawMyCanvas() {
        wx.showLoading()
        const that = this
        const query = wx.createSelectorQuery().in(this);
        console.log(query)
        query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
            size: true,
            scrollOffset: true
        }, data => {
            console.log(data)
            let width = data.width;
            let height = data.height;
            that.setData({
                width,
                height
            })
            setTimeout(() => {
                that.startDraw()
            }, 1500);
        }).exec()
    },
    startDraw() {
        let that = this
        console.log(that)
        let pixelRatio = (0, wx.getSystemInfoSync)().pixelRatio;
        console.log(pixelRatio)
        // 创建wxml2canvas对象
        let drawMyImage = new Wxml2Canvas({
            element: 'myCanvas', // canvas的id,
            obj: that, // 传入当前组件的this
            width: that.data.width * 3,
            height: that.data.height * 3,
            background: '#ff0000', // 生成图片的背景色
            progress(percent) { // 进度
                console.log(percent);
            },
            finish(url) { // 生成的图片
                console.log(url)
                wx.hideLoading()
                that.setData({
                    imgUrl:url
                })
                that.savePoster(url)
            },
            error(res) { // 失败原因
                console.log(res);
                wx.hideLoading()
            }
        }, this);
        let data = {
            // 获取wxml数据
            list: [{
                type: 'wxml',
                class: '.my_canvas .my_draw_canvas',  // my_canvas要绘制的wxml元素根类名， my_draw_canvas单个元素的类名（所有要绘制的单个元素都要添加该类名）
                limit: '.my_canvas', // 要绘制的wxml元素根类名
                x: 0,
                y: 0
            }]
        }
        // 绘制canvas
        drawMyImage.draw(data, this);
    },
    savePoster() {
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: that.data.imgUrl,
            success: function () {
                console.log("保存成功保存成功保存成功保存成功")
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    duration: 1500
                });
            },
            fail(err) {
                if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                    wx.showModal({
                        title: '提示',
                        content: '需要您授权保存相册',
                        showCancel: false,
                        success: modalSuccess => {
                            wx.openSetting({
                                success(settingdata) {
                                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                        wx.saveImageToPhotosAlbum({
                                            filePath: that.data.imgUrl,
                                            success: function () {
                                                wx.showToast({
                                                    title: '保存成功',
                                                    icon: 'success',
                                                    duration: 2000
                                                })
                                            },
                                        })
                                    } else {
                                        wx.showToast({
                                            title: '授权失败，请稍后重新获取',
                                            icon: 'none',
                                            duration: 1500
                                        });
                                    }
                                }
                            })
                        }
                    })
                }
            }
        })
    },
    qx(){
     wx.navigateTo({
       url: '/my/business_card_settings/business_card_settings',
     })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})